package com.laikan.reader.bookstore.fragment;

import android.annotation.SuppressLint;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.widget.SwipeRefreshLayout;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.view.animation.LinearInterpolator;
import android.webkit.*;
import android.webkit.WebSettings.RenderPriority;
import android.widget.ProgressBar;
import android.widget.RelativeLayout;
import android.widget.TextView;
import com.laikan.library.components.fragments.BasicFragment;
import com.laikan.library.utils.SPUtil;
import com.laikan.reader.R;
import com.laikan.reader.bookreader.activity.BookDesActivity;
import com.laikan.reader.bookstore.activity.CateRankActivity;
import com.laikan.reader.bookstore.activity.ClassTwo;
import com.laikan.reader.bookstore.activity.RecommendActivity;
import com.laikan.reader.comment.APIProtocol;
import com.laikan.reader.core.utils.ActivityUitl;
import com.laikan.reader.core.view.CircleProgressBar;

import java.net.URLDecoder;

@SuppressLint ({"ValidFragment", "JavascriptInterface"})
public class ClassifyPage extends BasicFragment {

    private static final String APP_CACAHE_DIRNAME = "/webcache";
    int type;
    private MyBroadcast broadcast;
    private ProgressBar progressbar;
    private String[] url = {APIProtocol.getRootURL2() + "index?group=", APIProtocol.getRootURL2() + "free?group=", APIProtocol.getRootURL2() + "ranking?group=", APIProtocol.getRootURL2() + "channel_sort?group=", APIProtocol.getRootURL2() + "finish?group="};
    private int flag = 1;
    private int positions;
    private View classifyPage;
    private WebView mWebView;
    private WebView mPullWebView;
    private boolean webflag = false;
    private RelativeLayout common_loaddata_notice;
    private TextView common_refresh_net,common_prompt_content;
    private String userId;
    private SwipeRefreshLayout mBookStorePageSwipeRefresh;
    private CircleProgressBar circleProgressBar;
    private boolean isLoadingSucess;
    private long mLoadDelaynternalTime;

    private WebViewClient webViewClient = new WebViewClient() {

        @Override
        public boolean shouldOverrideUrlLoading(WebView view, String url) {
//            if (ActivityUitl.isNetworkAvailable(mContext)) {
                if (!SPUtil.getBoolean("Single_click", false)) {
                    SPUtil.putBoolean("Single_click", true);
                    String[] bookUrl;
                    bookUrl = url.split("/");

                    if (url.contains("/book/") && !url.contains("android/2")) {

                            Intent intent = new Intent();
                            intent.setClass(mContext, BookDesActivity.class);
                            intent.putExtra("bookId", bookUrl[bookUrl.length - 1]);
                            startActivity(intent);
//                        Intent intent = new Intent();
//                        intent.setClass(mContext, BookStoreActivity.class);
//                        startActivity(intent);
                    }else if (url.contains("more")) {

                        String[] str = url.split("=");
                        Intent intent = new Intent();
                        intent.setClass(mContext, CateRankActivity.class);
                        intent.putExtra("mHtmlUrl", url);
                        intent.putExtra("title", URLDecoder.decode(str[str.length - 1]));
                        intent.putExtra("mode", "more");
                        startActivity(intent);

                    }else if (url.contains("special")) {
                        String[] str = url.split("=");
                        Intent intent = new Intent();
                        intent.setClass(mContext, CateRankActivity.class);
                        intent.putExtra("mHtmlUrl", url);
                        intent.putExtra("mode", "special");
                        intent.putExtra("title", URLDecoder.decode(str[str.length - 1]));
                        startActivity(intent);

                    }else if (url.contains("title") || url.contains("titleName")) {

                        String[] str = url.split("=");
                        Intent intent = new Intent();
                        intent.setClass(mContext, ClassTwo.class);
                        intent.putExtra("mHtmlUrl", url);
                        intent.putExtra("title", URLDecoder.decode(str[str.length - 1]));
                        startActivity(intent);

                    }else {
                        view.loadUrl(url + "&userId=" + userId);
                        SPUtil.putBoolean("Single_click", false);
                    }
                }
//            }else {
               SPUtil.putBoolean("Single_click", false);
//                mWebView.setVisibility(View.GONE);
//                common_loaddata_notice.setVisibility(View.VISIBLE);
//                common_prompt_content.setText(R.string.laikan_network_anomaly);
//            }
            return true;
        }

        public void onPageFinished(WebView view, String url) {
            dismissDialog();
            mBookStorePageSwipeRefresh.setRefreshing(false);
            flag = 1;
            mWebView.getSettings().setLoadsImagesAutomatically(true);
            progressbar.setVisibility(View.GONE);
            if (isLoadingSucess) {
                handler.sendEmptyMessage(1);
            }else {
                common_prompt_content.setText(R.string.laikan_data_load_failed);
                closeDelayLoading(System.currentTimeMillis());

            }
        }

        public void onPageStarted(WebView view, String url, android.graphics.Bitmap favicon) {
            isLoadingSucess = true;
            progressbar.setVisibility(View.VISIBLE);
            Animation am = AnimationUtils.loadAnimation(mContext, R.anim.myset);
            LinearInterpolator lir = new LinearInterpolator();
            am.setInterpolator(lir);
        }

        @Override
        public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) {
            isLoadingSucess = false;
        }
    };

    private Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case 0:
                    common_refresh_net.setOnClickListener(ClassifyPage.this);
                    mWebView.setVisibility(View.GONE);
                    common_loaddata_notice.setVisibility(View.VISIBLE);
                    circleProgressBar.setVisibility(View.INVISIBLE);
                    break;
                case 1:
                    common_refresh_net.setOnClickListener(ClassifyPage.this);
                    mWebView.setVisibility(View.VISIBLE);
                    common_loaddata_notice.setVisibility(View.GONE);
                    circleProgressBar.setVisibility(View.INVISIBLE);
                    break;
                case 2:
                    break;
            }

        }
    };

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        classifyPage = inflater.inflate(R.layout.classify, null, false);
        broadcast = new MyBroadcast();
        this.positions = getArguments().getInt("key");
        return classifyPage;
    }

    @Override
    protected void assignViews() {
        mWebView = (WebView)classifyPage.findViewById(R.id.classifyWebview);
        mBookStorePageSwipeRefresh = (SwipeRefreshLayout)classifyPage.findViewById(R.id.store_classify_swiperefresh);
        mBookStorePageSwipeRefresh.setColorSchemeResources(R.color.C_66ccdd);
        progressbar = (ProgressBar)getActivity().findViewById(R.id.progress);
        common_loaddata_notice = (RelativeLayout)classifyPage.findViewById(R.id.common_loaddata_notice);
        common_prompt_content = (TextView)classifyPage.findViewById(R.id.common_prompt_content);
        common_refresh_net = (TextView)classifyPage.findViewById(R.id.common_refresh_net);
        circleProgressBar = (CircleProgressBar)classifyPage.findViewById(R.id.comon_bgbar_loading);
    }

    public void closeDelayLoading(long currenttime) {
        if (currenttime < mLoadDelaynternalTime) {
            new Handler().postDelayed(new Runnable() {

                @Override
                public void run() {
                    handler.sendEmptyMessage(0);
                }
            }, 1000);
        }else {
            handler.sendEmptyMessage(0);
        }
    }

    @Override
    public void onResume() {
        super.onResume();
        IntentFilter filter = new IntentFilter("change_position");
        mContext.registerReceiver(broadcast, filter);
        SPUtil.putBoolean("Single_click", false);
    }

    @Override
    protected void initData() {
        type = SPUtil.getInt("select_setting", 1);
        userId = SPUtil.getString("user_id", "0");
        common_refresh_net.setOnClickListener(ClassifyPage.this);
        WebSettings webSetting = mWebView.getSettings();
        webSetting.setJavaScriptEnabled(true);
//        webSetting.setPluginState(WebSettings.PluginState.ON);
        webSetting.setAllowFileAccess(true);
        webSetting.setJavaScriptCanOpenWindowsAutomatically(true);//允许js弹出窗
        mWebView.addJavascriptInterface(new CallJavaInterface(), "android");// 通过调这个注册
        // 判断是否使用硬件加速
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
            mWebView.setLayerType(View.LAYER_TYPE_SOFTWARE, null);
        }
        mWebView.getSettings().setRenderPriority(RenderPriority.HIGH);
        mWebView.getSettings().setCacheMode(WebSettings.LOAD_DEFAULT);
        // 开启 DOM storage API 功能
        mWebView.getSettings().setDomStorageEnabled(true);
        // 开启 database storage API 功能
        mWebView.getSettings().setDatabaseEnabled(true);
        String cacheDirPath = getActivity().getFilesDir().getAbsolutePath() + APP_CACAHE_DIRNAME + url[positions];
        // 设置数据库缓存路径
        mWebView.getSettings().setDatabasePath(cacheDirPath);
        // 设置 Application Caches 缓存目录
        mWebView.getSettings().setAppCachePath(cacheDirPath);
        // 开启 Applicat ion Caches 功能
        mWebView.getSettings().setAppCacheEnabled(true);
        mWebView.getSettings().setAppCacheMaxSize(100);
        // 设置图片加载模式
        mWebView.getSettings().setBlockNetworkImage(false);
        // mWebView.getSettings().setBuiltInZoomControls(true);
        mWebView.getSettings().setUseWideViewPort(false);
        // 设置监听
        mWebView.setWebChromeClient(new MyWebChromeClient());
        mWebView.setWebViewClient(webViewClient);
        mWebView.getSettings().setLoadsImagesAutomatically(true);
        requestNetData(true);
        mBookStorePageSwipeRefresh.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {

            @Override
            public void onRefresh() {
                mBookStorePageSwipeRefresh.setRefreshing(false);
                //开始请求
                type = SPUtil.getInt("select_setting", 1);
                requestNetData(false);
                flag = 2;
                webflag = true;
            }
        });

    }

    private void requestNetData(boolean isload) {
        if (ActivityUitl.isNetworkAvailable(mContext)) {
            if (isload) {
                showDialog();
            }
            mWebView.getSettings().setCacheMode(WebSettings.LOAD_DEFAULT);
            mWebView.loadUrl(url[positions] + SPUtil.getInt("select_setting", 1) + "&userId=" + userId);
        }else {
            showErrorView(2);
        }
    }
    @Override
    protected void setListener() {

    }

    @Override
    protected void onClickEvent(View view) {
        switch (view.getId()){
            case R.id.common_refresh_net:
                common_refresh_net.setOnClickListener(null);
                circleProgressBar.setVisibility(View.VISIBLE);
                mLoadDelaynternalTime = System.currentTimeMillis() + 2000;
                if(ActivityUitl.isNetworkAvailable(mContext)){
                    mWebView.loadUrl(url[positions] + SPUtil.getInt("select_setting", 1) + "&userId=" + userId);
                }else {
                    common_prompt_content.setText(R.string.laikan_network_anomaly);
                    closeDelayLoading(System.currentTimeMillis());
                }
                break;
            default:
                break;
        }
    }

    private void change(int i) {
        SPUtil.putInt("select_setting", i);
    }

    @Override
    public void onPause() {

        super.onPause();
        mContext.unregisterReceiver(broadcast);
    }

    private class CallJavaInterface {

        @JavascriptInterface
        public boolean ignoreTouchCancel(boolean flag) {
            RecommendActivity main = (RecommendActivity)getActivity();
            if (flag) {
                main.pager.requestDisallowInterceptTouchEvent(true);
            }else {
                main.pager.requestDisallowInterceptTouchEvent(false);
            }
            return flag;
        }
    }

    private class MyWebChromeClient extends WebChromeClient {

        @Override
        public void onReceivedTitle(WebView view, String title) {

            super.onReceivedTitle(view, title);
        }

        @Override
        public void onProgressChanged(WebView view, int newProgress) {

            if (positions == 0) {

                progressbar.setProgress(newProgress + 3);
                if (newProgress == 100) {
                    progressbar.setVisibility(View.GONE);
                }else {
                    progressbar.setVisibility(View.VISIBLE);
                }
            }else {
                if (webflag) {
                    progressbar.setProgress(newProgress + 3);
                    if (newProgress == 100) {
                        progressbar.setVisibility(View.GONE);
                    }else {
                        progressbar.setVisibility(View.VISIBLE);
                    }
                }
            }
            webflag = false;
            super.onProgressChanged(view, newProgress);
        }
    }

    class MyBroadcast extends BroadcastReceiver {

        @Override
        public void onReceive(Context context, Intent intent) {
            mWebView.setVisibility(View.VISIBLE);
            common_loaddata_notice.setVisibility(View.GONE);
            type = SPUtil.getInt("select_setting", 1);
            if (intent.getIntExtra("current", 0) == positions) {
                if (ActivityUitl.isNetworkAvailable(mContext)) {
                    mWebView.loadUrl(url[positions] + SPUtil.getInt("select_setting", 1) + "&userId=" + userId);
                }else {
                    showErrorView(2);
                }
            }
            if (intent.getIntExtra("position", 0) > 0 && intent.getIntExtra("position", 0) < 4) {
                if (ActivityUitl.isNetworkAvailable(mContext)) {
                    mWebView.loadUrl(url[positions] + SPUtil.getInt("select_setting", 1) + "&userId=" + userId);
                }else {
                    showErrorView(2);
                }
            }
            flag = 2;
            webflag = true;
            mBookStorePageSwipeRefresh.setRefreshing(false);
        }
    }

    /**
     * @param type 为1  数据加载失败  为2 网络异常
     */
    private String showContent;
    private void showErrorView(int type){
        if(type == 1){
            showContent = getString(R.string.laikan_data_load_failed);
        }else if(type == 2){
            showContent = getString(R.string.laikan_network_anomaly);
        }
        mWebView.setVisibility(View.GONE);
        common_loaddata_notice.setVisibility(View.VISIBLE);
        common_prompt_content.setText(showContent);
    }
}
